package com.scau.service.impl;

import com.scau.common.exception.BusinessException;
import com.scau.dao.CounselorDao;
import com.scau.entity.Counselor;
import com.scau.service.CounselorService;
import com.scau.util.BeanUtil;
import com.scau.util.SessionUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

@Service
public class CounselorServiceImpl implements CounselorService {

    @Autowired
    private CounselorDao counselorDao;

    @Transactional
    @Override
    public void add(Counselor counselor) {

        counselor.setPassword(DigestUtils.md5DigestAsHex(counselor.getPassword().getBytes()));

        Counselor cache = counselorDao.save(counselor);
        BeanUtils.copyProperties(cache, counselor);
    }

    @Override
    public void login(String address, Counselor counselor) {
        Counselor account = counselorDao.findByPhoneAndPassword(counselor.getPhone(),
                 DigestUtils.md5DigestAsHex(counselor.getPassword().getBytes()));

        if (account == null) {
            throw new BusinessException("账号或者密码错误");
        } else {
            SessionUtil.putCounselor(address, account);
        }
    }

    @Override
    public Counselor findOne(Long counselorId) {
        Counselor counselor = counselorDao.findOne(counselorId);

        if (counselor == null) {
            throw new BusinessException("不存在该顾问");
        }
        return counselor;
    }

    @Override
    public Page<Counselor> findAll(Counselor counselor, Pageable pageable) {

        return counselorDao.findAll(Example.of(counselor), pageable);
    }

    @Transactional
    @Override
    public Counselor update(Counselor counselor) {

        if (counselor.getPassword() != null) {
            counselor.setPassword(DigestUtils.md5DigestAsHex(counselor.getPassword().getBytes()));
        }
        Counselor existing = this.findOne(counselor.getId());
        BeanUtil.copyNonNullProperties(counselor, existing);
        counselorDao.save(existing);
        return existing;
    }

    @Override
    public void delete(Long counselorId) {
        counselorDao.delete(counselorId);
    }
}
